import time
import urllib.parse
from typing import Optional
from model.主动发fetch import main
from model.浏览器樱花 import find
from model.全局page import douyin_browser
from model.url_download import download_video
from django.shortcuts import render
from django.http import JsonResponse
import re
import os
import sys
import urllib.parse
import requests
from django.http import StreamingHttpResponse, HttpResponseBadRequest, HttpResponse
from django.views.decorators.http import require_http_methods
import logging, traceback
from model.拿集数 import totals


logger = logging.getLogger(__name__)


def GodJin(request):
    return render(request, 'home.html')


def douyin(request):
    return render(request, 'douyin.html')


def douyin_page(request):
    return render(request, "douyin.html")


def douyin_fetch(request):
    try:
        if request.method != "POST":
            return JsonResponse({"ok": False, "error": "POST only"}, status=405)
        # 测试返回
        # print(request.POST['query'])
        if request.POST.get('mode') == 'single':
            s = request.POST['query']
            # return JsonResponse(main(request.POST['query'],douyin_browser.browser,douyin_browser.context))
            # print(request.POST['query'])
            if 'douyin' in s and 'http' in s:
                return JsonResponse(main(s,douyin_browser))
            else:
                return JsonResponse({"ok": False,'error':'这里要放抖音视频分享链接，例如：5.10 复҉制打开抖҉音，看看【小枝҉寄ͤ信（线上课报名中的作品】朋友都̑说3̷5mm镜͔҉头就是我的统治区̟！ ͤ35mm焦段.ͤ.. ̳̑https://v.douyin.com/U6XQBa0pWF0/ 03/21 cAG:/ b@A.TY '} )
        # 这里记得写返回主页视频的方法
        else:
            print(1)
            return JsonResponse({"ok": False, "error": "Not define"}, status=405)
    except Exception as e:
        logger.error("douyin_fetch 出错：%s\n%s", e, traceback.format_exc())
        return JsonResponse({"ok": False, "msg": str(e)}, status=500)


def douyin_download(request):
    url = request.POST.get('u')
    headers = {"Referer": "https://www.douyin.com/", "User-Agent": "Mozilla/5.0"}
    up = requests.get(url, headers=headers, stream=True, timeout=20, allow_redirects=True)
    up.raise_for_status()

    def gen():
        for chunk in up.iter_content(8192):
            if chunk:
                yield chunk

    resp = StreamingHttpResponse(gen(), content_type=up.headers.get('Content-Type', 'video/mp4'))
    resp['Content-Disposition'] = 'attachment; filename="video.mp4"'
    if up.headers.get('Content-Length'):
        resp['Content-Length'] = up.headers['Content-Length']
    return resp


def introduce(request):
    return render(request, 'introduce.html')


def free_video(request):
    return render(request, 'video.html')

def video_fetch(request):
    print('调用video')
    try:
        if request.method != "POST":
            return JsonResponse({"ok": False, "error": "POST only"}, status=405)
        # 测试返回
        # print(request.POST['query'])
        if request.POST.get('mode') == 'single':
            s = request.POST['query']



            return JsonResponse(find(s))

        else:
            print(1)
            return JsonResponse({"ok": False, "error": "Not define"}, status=405)
    except Exception as e:
        logger.error("video_fetch 出错：%s\n%s", e, traceback.format_exc())
        return JsonResponse({"ok": False, "msg": str(e)}, status=500)

def screen(request):
    return render(request, 'screen.html')

def version(request):
    return render(request, 'version.html')


def analysis(request):
    return render(request, 'analysis.html')

def feedback(request):
    return render(request,'feedback.html')

from django.http import JsonResponse

def api_video_play(request):
    if request.method != "POST":
        return JsonResponse({"ok": False, "error": "Method not allowed"}, status=405)

    url = request.POST.get('u')
    if not url:
        return JsonResponse({"ok": False, "error": "missing url"}, status=400)

    # 这里调用你自己的处理逻辑
    try:
        total = totals(url)   # 你自定义的函数
    except Exception as e:
        return JsonResponse({"ok": False, "error": str(e)}, status=500)

    # 成功返回
    print(total)
    return JsonResponse({
        "ok": True,
        "url": url,         # 如果要前端直接播放，可以把 url 返回去
        "episodes": str(total),     # 你要传的额外信息
    })

def select(request):
    return render(request, 'select.html')